import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { compression } from 'vite-plugin-compression2'

export default defineConfig(({ command, mode }) => {
  // 根据当前工作目录中的 `mode` 加载 .env 文件
  const env = loadEnv(mode, process.cwd())

  const plugins = [vue()]

  // 生产环境启用压缩
  if (env.VITE_USE_COMPRESS === 'true') {
    plugins.push(
      compression({
        algorithm: env.VITE_COMPRESS_TYPE === 'brotli' ? require('brotli') : require('zlib'),
        filename: env.VITE_COMPRESS_TYPE === 'brotli' ? '[path].br' : '[path].gz',
        deleteOriginalAssets: false, // 是否删除原始文件
        threshold: 10240, // 压缩阈值，单位为字节（默认为 10KB）
        compressionOptions: {
          // gzip 压缩配置
          level: 9 // 压缩级别，范围 1-9，值越大压缩率越高但更耗时
        }
      })
    )
  }

  return {
    plugins,
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    server: {
      host: '0.0.0.0',
      port: Number(env.VITE_PORT),
      open: true,
      proxy: env.VITE_USE_PROXY === 'true' ? {
        [env.VITE_API_BASE_URL]: {
          target: env.VITE_PROXY_TARGET,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp('^' + env.VITE_API_BASE_URL), '')
        }
      } : {}
    },
    build: {
      target: 'es2015',
      outDir: 'dist',
      assetsDir: 'assets',
      minify: 'terser',
      sourcemap: env.VITE_SOURCEMAP === 'true',
      terserOptions: {
        compress: {
          drop_console: env.VITE_DROP_CONSOLE === 'true',
          drop_debugger: env.VITE_DROP_DEBUGGER === 'true'
        }
      },
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: '[ext]/[name]-[hash].[ext]',
          manualChunks: {
            // 将第三方库单独打包
            'element-plus': ['element-plus'],
            'vue-vendor': ['vue', 'vue-router', 'pinia'],
            'echarts': ['echarts']
          }
        }
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `
            @use "sass:math";
            @use "sass:color";
          `
        }
      }
    }
  }
})
